package blog.juejin.socket.server;

import com.alibaba.fastjson.JSONObject;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * author : yeswater
 * date : 2024/8/8
 */

public class Server {
    public static void main(String[] args) {
        System.out.println("服务端启动");
        try {
            ServerSocket serverSocket = new ServerSocket(6301);
            while (true) {
                // 接受 socket 请求
                Socket socket = serverSocket.accept();
                new Thread(new ServerReader(socket)).start();
                new Thread(new ServerWriter(socket)).start();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        
    }
}

class ServerReader implements Runnable {
    private Socket socket;
    
    public ServerReader(Socket socket) {
        this.socket = socket;
    }
    
    @Override
    public void run() {
        try {
            ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
            
            while (true) {
                System.out.println(objectInputStream.readObject());
            }
            
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

class ServerWriter implements Runnable {
    private Socket socket;
    
    public ServerWriter(Socket socket) {
        this.socket = socket;
    }
    
    @Override
    public void run() {
        try {
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
            Scanner scanner = new Scanner(System.in);
            while (true) {
                System.out.println("服务端 请输入:");
                String str = scanner.nextLine();
                
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("type", "msg");
                jsonObject.put("content", str);
                
                objectOutputStream.writeObject(jsonObject);
                objectOutputStream.flush();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}


